package webdev.database;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import webdev.common.Common;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;


public class DatabaseHelp extends SQLiteOpenHelper {

	Common common = new Common();
	private SQLiteDatabase mDB;

	
	//"/storage/sdcard0/";
	public static String SDCARD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
	
	//private static String DB_PATH = "/mnt/sdcard/";
	private static final String DATABASE_NAME = "DanangTraveling.sqlite";
	private final Context mContext;
	
	
	public DatabaseHelp(Context context) {
    	super(context, DATABASE_NAME, null, 1);
        this.mContext = context;
    }	
	public void createDataBase() throws IOException{
		boolean dbExist = checkDataBase();
		if(dbExist){
			//do nothing if database already exist
		}
		else{
			
			//By calling this method and empty database will be created into the default system path
			//of your application so we are gonna be able to overwrite that database with our database.
			this.getReadableDatabase();
			try {
				copyDataBase();
				} 
				catch (IOException e)
				{
				throw new Error("Error copying database");
				}
			}
		}
		
	private boolean checkDataBase(){
		SQLiteDatabase checkDB = null;
		try {
			String myPath = SDCARD_PATH + DATABASE_NAME;
			checkDB = SQLiteDatabase.openDatabase(myPath, null,
					SQLiteDatabase.OPEN_READONLY);

		} catch (SQLiteException e) {
			// database does�t exist yet.
		}
		boolean isHave = false;
		if (checkDB != null) {
			isHave = true;
		} else {
			isHave = false;
		}
		if (checkDB != null) {
			checkDB.close();
		}
		// return checkDB != null ? true : false;
		return isHave;
	}
	private void copyDataBase() throws IOException{
		
		//Open your local db as the input stream
		InputStream myInput = mContext.getAssets().open(DATABASE_NAME);	
		// Path to the just created empty db
		//String outFileName = DB_PATH + DATABASE_NAME;	
		String outFileName = SDCARD_PATH + DATABASE_NAME;
		//Open the empty db as the output stream
		OutputStream myOutput = new FileOutputStream(outFileName);

		//transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;

		while ((length = myInput.read(buffer))>0){
		myOutput.write(buffer, 0, length);
		}
		//Close the streams
		myOutput.flush();
		myOutput.close();
		myInput.close();

	}

	public SQLiteDatabase openDataBase() throws SQLException{
		//Open the database
		String myPath = SDCARD_PATH + DATABASE_NAME;
		System.out.println("myPath:"+myPath);
		try {
			mDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mDB;
	}

    @Override
	public synchronized void close() {
 
    	    if(mDB != null)
    		    mDB.close();
 
    	    super.close();
 
	}
 
	@Override
	public void onCreate(SQLiteDatabase db) {
 
	}
 
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 
	}	
	
	/**
	*  Thuc hien execute query tra ve ket qua
	*  @param query
	*  @return: void
	*  @throws: 
	*/
	public void executeQuery(String query){
		try{
			if(mDB!=null)
			{
				if(mDB.isOpen()){
					mDB.close();
				} // end if
			}
			
			openDataBase();
			mDB.execSQL(query);
		}catch(Exception e){
			System.out.println("DATABASE ERROR ! !"+e);
		}finally
		{
			close();
		}
	}
	
	/**
	*  Thuc hien raw query
	*  @param query
	*  @return
	*  @return: Cursor
	*  @throws: 
	*/
	public Cursor selectQuery(String query){
		Cursor c1 = null;
		try{
			if(mDB!=null)
			{
				if(mDB.isOpen()){
					mDB.close();
				} // end if
			}// end if
			openDataBase();
			c1 = mDB.rawQuery(query,null);
		}catch(Exception e){
			System.out.println("DATABASE ERROR ! !");
		}/*finally
		{
			close();
		}*/
		return c1;
	}

}
